<template>
  <div>
        <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 商品列表 -->
    <el-card class="box-card">
      <el-alert title="消息提示的文案" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps align-center="" :active="activeName - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tabs标签页 -->
      <el-form :model="addGoodForm" :rules="addGoodFormRules" ref="addGoodFormRef" label-width="100px" label-position="top">
        <el-tabs @tab-click="tabClicked" v-model="activeName" tab-position="left" :before-leave="beforeLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="number" v-model="addGoodForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="number" v-model="addGoodForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="number" v-model="addGoodForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品参数" prop="goods_number">
              <el-cascader
                clearable
                style="width: 300px"
                v-model="addGoodForm.goods_cat"
                :options="cateList"
                :props="props"
                @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTabData" :key="item.attr_id">
               <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="cb" v-for="(cb, i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTabData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              action="http://115.159.87.220:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headersObj"
              :on-success="handleSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addGoodForm.goods_introduce"></quill-editor>
            <el-button style="margin-top: 20px" type="primary" @click="addGood">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片对话框 -->
    <el-dialog
      :visible.sync="showImgFlag"
      width="50%">
      <img style="width: 100%" :src="imgURL" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      activeName: '0',
      // 添加商品的表单数据
      addGoodForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 级联选择器选择的数据
        goods_cat: [513, 523, 529],
        pics: [],
        // 富文本编辑器内容
        goods_introduce: ''
      },
      // 表单验证规则
      addGoodFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ]
      },
      // 级联选择器的数据
      cateList: [],
      // 级联选择器的配置对象
      props: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 商品属性数据
      manyTabData: [],
      // 商品参数数据
      onlyTabData: [],
      // 图片上传组件的请求头数据
      headersObj: {
        Authorization: sessionStorage.getItem('token')
      },
      // 显示图片对话框
      showImgFlag: false,
      // 图片地址
      imgURL: ''
    }
  },

  created () {
    this.getCateList()
  },

  methods: {
    // 请求商品参数
    async getCateList () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    // 级联选择器选择后的处理函数
    handleChange () {
      if (this.addGoodForm.goods_cat.length !== 3) {
        this.addGoodForm.goods_cat = []
        return
      }
      console.log(this.addGoodForm.goods_cat)
    },
    // 切换tab前的回调函数
    beforeLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品参数')
        return false
      }
    },
    // tabs切换事件回调
    async tabClicked () {
      const id = this.addGoodForm.goods_cat[2]
      if (this.activeName === '1') {
        const { data: res } = await this.$axios.get(`categories/${id}/attributes`, { params: { sel: 'many' } })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
      } else if (this.activeName === '2') {
        const { data: res } = await this.$axios.get(`categories/${id}/attributes`, { params: { sel: 'only' } })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.onlyTabData = res.data
        console.log(this.onlyTabData)
      }
    },
    // 点击图片名回调函数
    handlePreview (file) {
      this.showImgFlag = true
      console.log(file)
      // this.imgURL = 'http://115.159.87.220:8888/' + file.response.data.tmp_path
      this.imgURL = file.url
    },
    // 移除图片时回调
    handleRemove (file) {
      console.log(file)
      const i = this.addGoodForm.pics.findIndex(item => {
        return item.pic === file.response.data.tmp_path
      })
      this.addGoodForm.pics.splice(i, 1)
    },
    // 文件上传成功
    handleSuccess (res) {
      console.log(res)
      this.addGoodForm.pics.push({ pic: res.data.tmp_path })
    },
    addGood () {
      this.$refs.addGoodFormRef.validate(async flag => {
        if (!flag) return this.$message.error('请填写必要的商品信息')
        const formData = JSON.parse(JSON.stringify(this.addGoodForm))
        formData.goods_cat = formData.goods_cat.join(',')
        formData.attrs = []
        this.manyTabData.forEach(item => {
          formData.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        this.onlyTabData.forEach(item => {
          formData.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })

        const { data: res } = await this.$axios.post('goods', formData)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$refs.addGoodFormRef.resetFields()
        this.$router.go(-1)
        console.log(res)
      })
    }
  }
}
</script>

<style scoped lang='less'>
.el-checkbox {
  margin-right: 0px;
}
</style>
